package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.dao.UserMapperCustom;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author cg.hu
 * @version 1.0.0
 * @date 2021-09-15 19:20
 * @description
 * @since 1.0.0
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    private static  final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserMapperCustom userMapperCustom;

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-16 9:38
     * @description    登录
     **/
    @Override
    public ServerResponse<User> login(String username, String password) {
        logger.info("username: {}", username);
        logger.info("password: {}", password);
        int resultCount = userMapperCustom.checkUsername(username);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        //  密码校验
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapperCustom.selectLogin(username, md5Password);
        if (null == user) {
            return ServerResponse.createByErrorMessage("密码错误");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功", user);
    }

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-16 9:38
     * @description    注册
     **/
    @Override
    public ServerResponse<String> register(User user) {
        int resultCount = 0;
        //resultCount = userMapperCustom.checkUsername(user.getUsername());
        //if (resultCount > 0) {
        //    return ServerResponse.createByErrorMessage("用户名已存在");
        //}
        //resultCount = userMapperCustom.checkEmail(user.getEmail());
        //if (resultCount > 0) {
        //    return ServerResponse.createByErrorMessage("email已存在");
        //}
        ServerResponse validResponse = this.checkValid(user.getUsername(), Const.USERNAME);
        if (!validResponse.isSuccess()) {
            return validResponse;
        }

        validResponse = this.checkValid(user.getEmail(), Const.EMAIL);
        if (!validResponse.isSuccess()) {
            return validResponse;
        }

        user.setRole(Const.Role.ROLE_CUSTOMER);
        // MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        resultCount = userMapper.insert(user);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败");
        }

        return ServerResponse.createBySuccessMessage("注册成功");
    }

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-16 10:33
     * @description    校验参数有效性
     **/
    @Override
    public ServerResponse<String> checkValid(String str, String type) {
        if (StringUtils.isBlank(str)) {
            return ServerResponse.createByErrorMessage("");
        }
        int resultCount = 0;

        if (Const.USERNAME.equals(type)) {
            resultCount = userMapperCustom.checkUsername(str);
            if (resultCount == 0) {
                return ServerResponse.createByErrorMessage("用户名不存在");
            }
        }
        if (Const.EMAIL.equals(type)) {
            resultCount = userMapperCustom.checkEmail(str);
            if (resultCount > 0) {
                return ServerResponse.createByErrorMessage("email已存在");
            }
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-16 11:08
     * @description    忘记密码
     **/
    @Override
    public ServerResponse<String> selectQuestion(String username) {
        int resultCount = 0;
        ServerResponse validResponse = this.checkValid(username, Const.USERNAME);
        if (validResponse.isSuccess()) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String question = userMapperCustom.selectQuestionByUsername(username);
        if (StringUtils.isBlank(question)) {
            return ServerResponse.createByErrorMessage("找回密码的问题是空的");
        }
        return ServerResponse.createBySuccess(question);
    }

    /**
     * @author cg.hu
     * @version 1.0.0   
     * @date 2021-09-16 11:35
     * @description
     **/
    @Override
    public ServerResponse<String> checkAnswer(String username, String question, String answer) {
        int resultCount = 0;
        resultCount = userMapperCustom.checkAnswer(username, question, answer);
        if (resultCount <= 0) {
            return ServerResponse.createByErrorMessage("问题的答案错误");
        }
        // 说明问题和答案是这个用户的，并且是正确的
        String forgetToken = UUID.randomUUID().toString();
        TokenCache.setKey(TokenCache.TOKEN_PREFIX+username, forgetToken);
        return ServerResponse.createBySuccess(forgetToken);
    }


    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-16 14:00
     * @description    忘记密码重置密码
     **/
    @Override
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken) {
        if (StringUtils.isBlank(forgetToken)) {
            return ServerResponse.createByErrorMessage("forgetToken不能为空");
        }
        ServerResponse validResponse = this.checkValid(username, Const.USERNAME);
        if (validResponse.isSuccess()) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if (StringUtils.isBlank(token)) {
            return ServerResponse.createByErrorMessage("token无效");
        }
        if (!StringUtils.equals(forgetToken, token)) {
            return ServerResponse.createByErrorMessage("token失效");
        }
        String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
        int rowCount = userMapperCustom.updatePasswordByUsername(username, md5Password);
        if (rowCount <= 0) {
            return ServerResponse.createByErrorMessage("重置密码失败");
        }
        return ServerResponse.createBySuccessMessage("重置密码成功");
    }

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-16 14:41
     * @description    重置密码
     **/
    @Override
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, User user) {
        // 防止横向越权，要校验一下这个用户的旧密码，一定要指定是这个用户
        int resultCount = userMapperCustom.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        resultCount = userMapper.updateByPrimaryKeySelective(user);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("重置密码失败");
        }
        return ServerResponse.createBySuccessMessage("重置密码成功");
    }

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-16 15:10
     * @description    更新用户信息
     **/
    @Override
    public ServerResponse<User> updateInformation(User user) {
        // username是不能被更新的
        // email也要进行校验
        int resultCount = 0;
        resultCount = userMapperCustom.checkEmailByUserId(user.getEmail(), user.getId());
        if (resultCount > 0) {
            return ServerResponse.createByErrorMessage("email已存在，请更换email再尝试更新");
        }
        User updateUser = new User();
        BeanUtils.copyProperties(user, updateUser);
        resultCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("更新信息失败");
        }
        return ServerResponse.createBySuccess("更新信息成功", updateUser);
    }

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-16 16:29
     * @description    获取用户信息
     **/
    @Override
    public ServerResponse<User> getInformation(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return ServerResponse.createBySuccessMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    // backend


    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-17 10:53
     * @description    校验用户角色
     **/
    @Override
    public ServerResponse checkAdminRole(User user) {
        if (null != user && user.getRole().intValue() == Const.Role.ROLE_ADMIN) {
            return ServerResponse.createBySuccess();
        }

        return ServerResponse.createByError();
    }
}
